//1. 引用公共包
var PublicHttp = require("http");
var PublicUrl = require("url");
var PublicQuerystring = require('querystring');
const PublicZlib = require('node:zlib');
const PublicFs=require("fs");
//const PublicRequest = require('sync-request');
//var PublicBodyParser = require('body-parser');
//var PublicPathLib = require('path');
const PublicTruf=require("@turf/turf")
var PublicData={};//定义一个全局变量，接口中可以给该变量赋值
//2. 引用自己写的包
// var Config = require("./config");

let ReadConfig=function(filePath){
	let fd=PublicFs.openSync(filePath,"r");
	let info=PublicFs.fstatSync(fd);
	let buf=Buffer.alloc(info.size);
	PublicFs.readSync(fd,buf,0,info.size,null);
	let item=buf.toString().split("\n");
	let LastName="",data={};
	for(let i in item){
		try{
			LastName=item[i].match(/^\s*\[[\s]*([\S]+)[\s]*\]/)[1];
			data[LastName]={}
		}catch(e){
			//TODO handle the exception
			try{
				let v=item[i].match(/\s*(\S+)\s*=\s*([^\t\r\n]+)\s*[\t\r\n]*/);
				if(LastName!=""){
					try{
						data[LastName][v[1]]=JSON.parse(v[2]);
					}catch(e){
						//TODO handle the exception
						data[LastName][v[1]]=v[2];
					}
				}
				
			}catch(e){
				//TODO handle the exception
			}
		}
	}
	return data;
}
let ReadFile=function(path){
	let fd=PublicFs.openSync(path,"r");
	let info=PublicFs.fstatSync(fd);
	let buf=Buffer.alloc(info.size);
	let size=PublicFs.readSync(fd,buf,0,info.size,null);
	PublicFs.closeSync(fd);
	return {"content":buf.toString(),"info":info};
};
//3. 读取并解析系统配置文件
var SystemConfig = ReadConfig("./Config.ini")

console.log(SystemConfig)

//4. 读取handle.js
let readtemp=ReadFile("./handle.js");
var HandleObject=eval(readtemp.content);
var HandleTime=readtemp.info.mtimeMs;

//7. 创建一个服务器
var server = PublicHttp.createServer(function(req, res) {
	//1. 监听http body，当有一段数据到达的时候
	var Body = '';
	req.on('data', function(data) {
		Body += data;
	});
	
	req.on('end', function() {
		try {
			if (Body.substr(0, 1) == "{" || Body.substr(0, 1) == "[") {
				Body = JSON.parse(Body)
			}
		} catch (e) {
			//TODO handle the exception
		}
		//动态加载handle.js，一旦handle.js有变更，不需要重启服务器，立即生效。
		let fd=PublicFs.openSync("./handle.js","r")
		let info=PublicFs.fstatSync(fd);
		PublicFs.closeSync(fd)
		
		if(info.mtimeMs!=HandleTime){
			let readtemp=ReadFile("./handle.js");
			HandleObject=eval(readtemp.content);
			HandleTime=readtemp.info.mtimeMs;
		}
		HandleObject.Handle(req,res,Body)
	});
});

//运行服务器，监听3000端口（端口号可以任改）
server.listen(SystemConfig.webserver.port, SystemConfig.webserver.host);

// 终端打印如下信息
console.log('运行成功  端口：'+SystemConfig.webserver.port)
console.log('访问接口  http://127.0.0.1:'+SystemConfig.webserver.port+'/demo/117.82649822717218/36.76007283980236')